package com.uduemc.biso.node.web.api.service.fegin.impl;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.uduemc.biso.core.utils.RestResult;
import com.uduemc.biso.node.core.entities.SComponentForm;
import com.uduemc.biso.node.core.feign.SComponentFormFeign;
import com.uduemc.biso.node.core.utils.RestResultUtil;
import com.uduemc.biso.node.web.api.service.fegin.SComponentFormService;

@Service
public class SComponentFormServiceImpl implements SComponentFormService {

	@Resource
	private SComponentFormFeign sComponentFormFeign;

	@Resource
	private ObjectMapper objectMapper;

	@Override
	public SComponentForm insert(SComponentForm sComponentForm) throws IOException {
		RestResult restResult = sComponentFormFeign.insert(sComponentForm);
		return RestResultUtil.data(restResult, SComponentForm.class);
	}

	@Override
	public SComponentForm findSComponentForm(long id, long hostId, long siteId) throws IOException {
		RestResult restResult = sComponentFormFeign.findOne(id);
		SComponentForm data = RestResultUtil.data(restResult, SComponentForm.class);
		if (data != null && data.getHostId() != null && data.getSiteId() != null) {
			if (data.getHostId().longValue() == hostId && data.getSiteId().longValue() == siteId) {
				return data;
			}
		}
		return null;
	}

	@Override
	public SComponentForm findSComponentForm(long id, long hostId, long siteId, long formId) throws IOException {
		SComponentForm findSComponentForm = findSComponentForm(id, hostId, siteId);
		if (findSComponentForm == null || findSComponentForm.getFormId() == null) {
			return null;
		}
		if (findSComponentForm.getFormId().longValue() == formId) {
			return findSComponentForm;
		}
		return null;
	}

	@Override
	public List<SComponentForm> findInfosByHostFormIdStatus(long hostId, long formId, short status) throws IOException {
		RestResult restResult = sComponentFormFeign.findInfosByHostFormIdStatus(hostId, formId, status);

		@SuppressWarnings("unchecked")
		List<SComponentForm> data = (List<SComponentForm>) RestResultUtil.data(restResult,
				objectMapper.getTypeFactory().constructParametricType(ArrayList.class, SComponentForm.class));

		return data;
	}

	@Override
	public SComponentForm update(SComponentForm sComponentForm) throws IOException {
		RestResult restResult = sComponentFormFeign.updateById(sComponentForm);
		return RestResultUtil.data(restResult, SComponentForm.class);
	}
}
